package br.com.tiespec.web.Util;

import java.io.IOException;

import javax.faces.FacesException;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import br.com.tiespec.model.Modelo.ClientePortal;
import br.com.tiespec.model.Modelo.Usuario;
import br.com.tiespec.web.ManagedBean.ContextoBean;

public class WebUtil {
	
	public static String gerarLinkAtivacao(){
		FacesContext context = FacesContext.getCurrentInstance();  
		HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();  
		String urlAtual = request.getRequestURL().toString();
		String arrayUrl[];
		arrayUrl=urlAtual.split("/");
		String novaUrl="";
		for(int i=0; i<arrayUrl.length; i++){
			if(i<=5){
				if(i==0){ novaUrl = novaUrl+ arrayUrl[i]; }
				if(i==1){ novaUrl = novaUrl+"//"+ arrayUrl[i]; }
				if(i>1){ novaUrl = novaUrl + arrayUrl[i] + "/";}
			}
		}
		novaUrl=novaUrl+"confirmacaoEmail.jsf?id=";
		return novaUrl;
	}

	public static void redirecionar(String destino){
		FacesContext ctx = FacesContext.getCurrentInstance();
		ExternalContext extContext = ctx.getExternalContext();
		String url = extContext.encodeActionURL(ctx.getApplication().getViewHandler().getActionURL(ctx, destino));
		try {
			extContext.redirect(url);
		} catch (IOException ioe) {
			throw new FacesException(ioe);
		}
	}

	public static Usuario getUsuarioLogado(){
		FacesContext context = FacesContext.getCurrentInstance();
		ContextoBean bean = (ContextoBean) context.getApplication()
				.evaluateExpressionGet(context, "#{contextoBean}", ContextoBean.class);
		if(bean!=null){
			Usuario usuario = bean.getUsuario();
			if(usuario != null && usuario.getId() != null){
				return usuario;
			}
		}
		return null;
	}
	
	public static ClientePortal getClientePortalEmContexto(){
		FacesContext context = FacesContext.getCurrentInstance();
		ContextoBean bean = (ContextoBean) context.getApplication()
				.evaluateExpressionGet(context, "#{contextoBean}", ContextoBean.class);
		if(bean!=null){
			ClientePortal clientePortalInstance = bean.getClienteEmContexto();
			if(clientePortalInstance != null && clientePortalInstance.getId() != null){
				return clientePortalInstance;
			}
		}
		return null;
	}

	public static void setDataTableRows(Integer rows){
		FacesContext context = FacesContext.getCurrentInstance();
		ContextoBean bean = (ContextoBean) context.getApplication()
				.evaluateExpressionGet(context, "#{contextoBean}", ContextoBean.class);
		if (bean != null)
			bean.setDataTableRows(rows);
	}
}
